#!/usr/bin/python
# -*- coding:utf-8 -*-
# @time: 2021/6/7 3:14 下午

import time
import syslog

from models.audit_log import AuditLog
from apps.global_config.serializer import get_global_config


def log_msg(level, msg, *args, **kwargs):
    syslog.syslog(level, msg, *args, **kwargs)


def log_info(msg, *args, **kwargs):
    log_msg(syslog.LOG_INFO, msg, *args, **kwargs)


def log_warn(msg, *args, **kwargs):
    log_msg(syslog.LOG_WARNING, msg, *args, **kwargs)


def log_debug(msg, log_level, *args, **kwargs):
    if log_level == 3:
        log_msg(syslog.LOG_DEBUG, msg, *args, **kwargs)


def log_err(msg, *args, **kwargs):
    log_msg(syslog.LOG_ERR, msg, *args, **kwargs)


def audit_log(request, **kwargs):
    """
    操作日志记录，格式为
    time, operator, domain, property_name, ip, source, module, action, type, desc=>{ desc.index_key, desc.detail}
    """
    global_config = get_global_config()
    if not getattr(global_config, "operate_log", False):
        return
    if not getattr(request.user, 'username', ''):  # 无用户不记录日志
        return
    data = {
        "time": kwargs.get("time") or int(time.time()),
        "source": kwargs.get("source") or "cyd",
        "operator": kwargs.get("operator") or getattr(request.user, 'username', ''),
        'group': [item.group for item in kwargs.get("group", []) or getattr(request.user, 'group', [])],
        "domain": kwargs.get("domain", ""),
        "property_name": kwargs.get("property_name", ""),
        "ip": request.META.get("HTTP_X_FORWARDED_FOR")
        or request.META.get("REMOTE_ADDR", ""),
        "module": kwargs.get("module"),
        "action": kwargs.get("action"),
        "type": kwargs.get("type"),
        "desc": kwargs.get("desc"),
    }
    audit_log_obj = AuditLog(**data)
    audit_log_obj.save()


def login_log(request=None, **kwargs):
    """
    登录日志
    """
    global_config = get_global_config()
    if not getattr(global_config, "login_log", False):
        return
    operator = kwargs.get("operator", "")
    ip = kwargs.get("ip", "")
    if request:
        operator = operator or request.user.username
        ip = (
            ip
            or request.META.get("HTTP_X_FORWARDED_FOR")
            or request.META.get("REMOTE_ADDR")
            or "未知"
        )
    data = {
        "time": kwargs.get("time") or int(time.time()),
        "operator": operator,
        "ip": ip,
        "module": "login",
        "source": "cyd",
        "type": kwargs.get("type"),
        "status": kwargs.get("status"),
        "desc": {"detail": kwargs.get("desc")},
        'group': [item.group for item in kwargs.get("group", []) or kwargs.get('group', [])]
    }
    login_log_obj = AuditLog(**data)
    login_log_obj.save()


def log_login_success(request, group=None):
    login_log(
        request,
        type="login",
        status="success",
        desc="登录成功",
        operator=request.data.get('username'),
        group=group
    )


def log_login_fail(request, error=""):
    login_log(
        request,
        type="login",
        status="fail",
        desc=f"登录失败:{error}",
        operator=request.data.get('username'),
    )


def log_logout(request, username):
    login_log(
        request,
        type="logout",
        status="success",
        desc=f"退出登录",
        operator=username
    )
